package com.vhall.component.service.room.impl;

import cn.hutool.core.util.StrUtil;
import com.vhall.component.service.room.CallBackService;
import com.vhall.component.service.room.CallRecordService;
import com.vhall.component.service.room.LiveService;
import com.vhall.component.service.room.event.handler.AbstractEventHandler;
import com.vhall.component.service.room.event.handler.HandlerContext;
import com.vhall.component.service.room.event.handler.RedirectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author 65782
 * @date 2021-06-08 14:40
 */
@Slf4j
@Service
public class CallBackServiceImpl implements CallBackService {


    @Value("${paas.apps.lite.appId}")
    public String appId;
    @Value("${paas.apps.lite.appSecret}")
    public String appSecret;

    @Autowired
    private LiveService liveService;

    @Autowired
    private CallRecordService callRecordService;

    static final String EVENT = "event";
    @Autowired
    private HandlerContext handlerContext;
    @Autowired
    private RedirectUtil redirectUtil;
    @Value("${old.callback.document.url}")
    private String callbackUrl;
    @Value("${old.callback.live.url}")
    private String liveCallbackUrl;
    @Value("${old.callback.record.url}")
    private String recordCallbackUrl;

    @Override
    public String liveIndex(Map<String, Object> callBack) {
        redirectUtil.redirect(liveCallbackUrl, callBack);
        invokeHandle(callBack);
        return "success";
    }

    @Override
    public String recordIndex(Map<String, Object> callBack) {
        log.warn("音视频回调:{},{}", appId, callBack);
        redirectUtil.redirect(recordCallbackUrl, callBack);
        invokeHandle(callBack);
        return "success";
    }


    @Override
    public void liveCallbackHandler(Map<String, Object> callBack) {
        invokeHandle(callBack);
    }

    /**
     * 执行事件处理
     *
     * @param callBack 事件内容
     */
    private void invokeHandle(Map<String, Object> callBack) {
        String event = (String) callBack.get(EVENT);
        if (StrUtil.isNotBlank(event)) {
            // 根据事件获取该事件的handler
            AbstractEventHandler eventHandler = handlerContext.getInstance(event);
            if (eventHandler != null) {
                eventHandler.handle(callBack);
            } else {
                log.info("没有找到[{}]事件的handler", event);
            }
        }
    }
}
